# coding=utf-8
from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import db
from info.models import News, User, Comment, CommentLike
from info.utils.commom import user_login_data
from info.utils.response_code import RET
from . import news_blue


# 关注与取消关注
# 请求路径: /news/followed_user
# 请求方式: POST
# 请求参数:user_id,action
# 返回值: errno, errmsg
@news_blue.route('/followed_user', methods=['POST'])
@user_login_data
def followed_user():

    #0,判断用户是否登陆
    if not g.user:
        return jsonify(errno=RET.NODATA,errmsg="用户未登录")

    #1, 获取参数
    author_id = request.json.get("user_id")
    action = request.json.get("action")

    #2, 校验参数
    #为空校验
    if not all([author_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    #操作类型校验
    if not action in ["follow","unfollow"]:
        return jsonify(errno=RET.DATAERR,errmsg="操作类型有误")

    #取出作者对象,判断是否存在
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取作者失败")

    if not author:
        return jsonify(errno=RET.NODATA,errmsg="作者不存在")

    #3,数据入库
    if action == "follow":
        if g.user not in author.followers:
            author.followers.append(g.user)
    else:
        if g.user in author.followers:
            author.followers.remove(g.user)

    #4,返回响应
    return jsonify(errno=RET.OK,errmsg="success")


# 评论点赞
# 请求路径: /news/comment_like
# 请求方式: POST
# 请求参数:comment_id,action,g.user
# 返回值: errno,errmsg
@news_blue.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():

    #0,判断用户登陆状态
    if not g.user:
        return jsonify(errno=RET.PARAMERR,errmsg="用户未登录")

    #1, 获取参数
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")

    #2, 校验参数
    # 2,1 为空校验, 判断操作类型
    if not all([comment_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    if not action in ["add","remove"]:
        return jsonify(errno=RET.DATAERR,errmsg="操作类型有误")

    #2,2 获取评论对象,判断是否存在
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询评论有误")

    if not comment:
        return jsonify(errno=RET.NODATA,errmsg="评论不存在")


    #3, 操作数据库(点赞,取消点赞)
    try:
        if action == "add":

            #判断用户是否点过赞
            comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,CommentLike.comment_id == comment_id).first()

            if not comment_like:
                #创建点赞对象
                comment_like = CommentLike()
                comment_like.comment_id = comment_id
                comment_like.user_id = g.user.id

                #添加到数据库
                db.session.add(comment_like)

                #将评论的点赞数量+1
                comment.like_count += 1
                db.session.commit()
        else:
            # 判断用户是否点过赞
            comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,
                                                    CommentLike.comment_id == comment_id).first()

            if comment_like:
                #删除点赞对象
                db.session.delete(comment_like)

                #点赞数量-1
                if comment.like_count > 0:
                    comment.like_count -= 1

                # 提交数据库
                db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="操作失败")

    #4, 返回响应
    return jsonify(errno=RET.OK,errmsg="操作成功")


@news_blue.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():

    if not g.user:
        return jsonify(errno=RET.LOGINERR,errmsg="用户未登录")
    # 1 获取参数 news_id,comment,parent_id
    news_id = request.json.get("news_id")
    content = request.json.get("comment")
    parent_id = request.json.get("parent_id")

    #2,校验参数
    #2,1为空校验
    if not all([news_id,content]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    #2,2新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="新闻查询失败")

    if not news:
        return jsonify(errno=RET.NODATA,errmsg="新闻不存在")

    #3,数据入库
    comment = Comment()
    comment.user_id = g.user.id
    comment.news_id = news_id
    comment.content = content

    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg="评论失败")

    #4,返回响应
    return jsonify(errno=RET.OK,errmsg="评论成功",data=comment.to_dict())


@news_blue.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    if not g.user:
        return jsonify(error=RET.LOGINERR,errmsg="用户未登录")

    # 1 获取参数news_id,action
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2 参数校验
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="新闻查询失败")

    if not news:
        return jsonify(errno=RET.DATAERR,errmsg="没有这条新闻")

    if not action in ["collect","cancel_collect"]:
        return jsonify(errno=RET.DATAERR,errmsg="操作有误")

    # 3 执行收藏和取消收藏,数据入库
    if action == "collect" and not news in g.user.collection_news:
        g.user.collection_news.append(news)
    if action == "cancel_collect" and news in g.user.collection_news:
        g.user.collection_news.remove(news)
    return jsonify(errno=RET.OK,errmsg="操作成功")


# @news_blue.route('/<int:news_id>')
# @user_login_data
# def news_detail(news_id):
#     # news_id自动带数据过来,Todo前端分析
#     try:
#         news = News.query.get(news_id)
#     except Exception as e:
#         current_app.logger.error(e)
#
#     # 2, 判断是否存在
#     if not news:
#         abort(404)
#
#     # 右上角用户名称显示
#     # 1 数据获取
#     # user_id = session.get("user_id")
#     # 2 根据用户编号获取对用户对象
#     # user = None
#     # if user_id:
#         # user = User.query.filter(User.id == user_id).first()
#         # user = User.query.get(user_id)
#
#     # 热门新闻排行
#     try:
#         news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
#         # news_list = News.query.order_by(News.clicks.desc()).limit(10)
#     except Exception as e:
#         current_app.logger.error(e)
#
#     clicks_news_list = []
#     for news in news_list:
#         clicks_news_list.append(news.to_dict())
#
#
#     #2,1 判断当前新闻是否在用户的收藏列表中
#     #假设未收藏
#     is_collected = False
#     # 当前用户登陆了, 并且当前新闻在用户的收藏列表中:
#     if g.user and news in g.user.collection_news:
#         is_collected = True
#
#     #2,2查询当前新闻所有的评论信息
#     try:
#         comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DBERR,errmsg="获取评论失败")
#
#     # 1 获取用户所有点赞
#     comments_like = CommentLike.query.filter(CommentLike.user_id == g.user.id).all()
#
#     # 2 点赞的id列表
#     comments_like_ids =[]
#     for comment_like in comments_like:
#         comments_like_ids.append(comment_like.comment_id)
#
#     #2,3将评论对象列表,转成字典列表
#     comment_list = []
#     for comment in comments:
#         comm_dict = comment.to_dict()
#         comm_dict["is_like"] = False
#         if g.user and comment.id in comments_like_ids:
#             comm_dict["is_like"] = True
#         comment_list.append(comm_dict)
#
#     data = {
#         "clicks_news_list": clicks_news_list,
#         "news_info": news.to_dict(),
#         "user_info": g.user.to_dict() if g.user else "",
#         "is_collected": is_collected,
#         "comments": comment_list,
#     }
#
#     return render_template("news/detail.html", data=data)

# 新闻详情展示(用户)
# 请求路径: /news/<int:news_id>
# 请求方式: GET
# 请求参数:news_id
# 返回值: detail.html页面, 用户data字典数据
@news_blue.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):

    # #0,获取session用户编号
    # user_id = session.get("user_id")
    #
    # #0.1,根据用户编号获取对象
    # user = None
    # if user_id:
    #     user = User.query.get(user_id)

    #1, 根据新闻编号获取新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    #2, 判断是否存在
    if not news:
        abort(404)


    # 热门新闻排行
    # try:
    #     news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    #     # news_list = News.query.order_by(News.clicks.desc()).limit(10)
    # except Exception as e:
    #     current_app.logger.error(e)
    #
    # clicks_news_list = []
    # for news in news_list:
    #     clicks_news_list.append(news.to_dict())


    #2,1 判断当前新闻是否在用户的收藏列表中
    is_collected = False #假设未收藏

    # 当前用户登陆了, 并且当前新闻在用户的收藏列表中:
    if g.user and news in g.user.collection_news:
        is_collected = True


    #2,2查询当前新闻所有的评论信息
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取评论失败")

    # 2,2,1 查询用户所有的点赞
    comment_likes = []
    if g.user:
        comment_likes = CommentLike.query.filter(CommentLike.user_id == g.user.id).all()

    # 2,2,2 找出用户点赞过的评论编号
    comment_like_ids = []

    for comment_like in comment_likes:
        comment_like_ids.append(comment_like.comment_id)

    #2,3将评论对象列表,转成字典列表
    comment_list = []
    for comment in comments:
        comm_dict = comment.to_dict()

        #添加点赞key,假设没有点赞
        comm_dict["is_like"] = False

        #用户需要登陆, 当前评论在用户点赞过的编号里面
        if g.user and comment.id in comment_like_ids:
            comm_dict["is_like"] = True

        comment_list.append(comm_dict)

    #2,4 判断当前用户是否关注过,新闻作者
    is_followed = False
    if news.user and g.user in news.user.followers:
        is_followed = True

    #3, 将新闻对象,转成字典数据
    data = {
        # "clicks_news_list": clicks_news_list,
        "news_info":news.to_dict(),
        "user_info":g.user.to_dict() if g.user else "",
        "is_collected":is_collected,
        "comments":comment_list,
        "is_followed":is_followed
    }

    #4,携带数据,渲染页面
    return render_template('news/detail.html',data=data)